#include "tcpclientsocket.h"
#include "dialog.h"
#include "ui_dialog.h"
#include <QThread>
#include "aTcpServer.h"
#include "macro.h"
#include "DBO/protocal.h"
#include "DBO/dbointhread.h"
#include "macro.h"


tcpClientSocket::tcpClientSocket(QObject *parent) :
    QTcpSocket(parent)
{
    temp=new QByteArray();
    connect(this,SIGNAL(readyRead()),this,SLOT(readClient()));
    connect(this,SIGNAL(disconnected()),this,SLOT(deleteLater()));
}

void tcpClientSocket::readClient()
{
    bool ok;
    qint64 counter=0;
    temp->append(readAll());
    ((WeatherStation*)(parent()->parent()))->slotApdTxt("TCP data come. Total size is"+QByteArray::number(temp->size())+
                    " It begins with "+temp->toHex().mid(0,60));

    while(temp->size()>=14&&(!temp->startsWith("ERR")&&!temp->startsWith("INFO")&&!temp->startsWith("WARN")))
    {
        if(counter%30==29) //每连续处理20个包，处理下事件
        {
            qApp->processEvents(QEventLoop::AllEvents,MAX_ProcessEvents_MiliSecs); //处理其他事务
        }
        counter++;
        QByteArray head=temp->mid(0,2).toHex();


        if(!mapHeadProtocal.contains(head))
        {
            QMutex mutex;
            mutex.lock();
            if(!((WeatherStation*)(parent()->parent()))->dboInThread->mapHeadProtocal.contains(head))
                ((WeatherStation*)(parent()->parent()))->dboInThread->readProtocolTable(head);
            if(!((WeatherStation*)(parent()->parent()))->dboInThread->mapHeadProtocal.contains(head))
            {
                emit sigErrorInfo("ERROR:No suitable protocol in WSN found whose head is "+head);
                mutex.unlock();
                return;
            }
            else
                mapHeadProtocal.insert(head,((WeatherStation*)(parent()->parent()))->dboInThread->mapHeadProtocal.value(head));
            mutex.unlock();
        }

        Protocal curProtoc=mapHeadProtocal.value(head);


        if(curProtoc.pHeader!=head)
        {
            ((WeatherStation*)(parent()->parent()))->slotApdTxt("Head not correct. Tcp buffer is cleared.");
            temp->clear();
            return;
        }
        if(temp->size()<(curProtoc.pLenPos/8+curProtoc.pLenSize/8))
        {
            break;
        }
        qint32 len=temp->mid(curProtoc.pLenPos/8,curProtoc.pLenSize/8).toHex().toLongLong(&ok,16);
        if(temp->size()>=(len+4))
        {
            ((WeatherStation*)(parent()->parent()))->slotApdTxt("Correct TCP packet");
            QByteArray dataGram=temp->mid(0,len+4);
            ((WeatherStation*)(parent()->parent()))->analyzeGWDatagram(dataGram,this->peerAddress(),this->peerPort(),true);
            temp->remove(0,len+4);
        }
        else
            break;
    }
    if(temp->startsWith("ERR")||temp->startsWith("INFO")||temp->startsWith("WARN"))
    {
        ((WeatherStation*)(parent()->parent()))->slotApdTxt("Head not correct. Tcp buffer is cleared.");
        temp->clear();
    }

}

/*
 断开连接时，调用该析构函数，对数据库表格的内容进行处理,并清除addrSocketMap中的相关内容
 */
tcpClientSocket::~tcpClientSocket()
{
    qDebug()<<"one socket is deleting";
    ((aTcpServer*)parent())->numOfConnection--;
}

